//[0,1,0,1,2,3,4,5,2]
function getNext (subStr = 'issip', next = [0]) {
  let i = 1
  let j = 0
  while (i < subStr.length) {
    if (subStr[i] === subStr[j]) {
      next[i] = j + 1
      i++
      j++
    } else {
      if (j === 0) {
        next[i] = 0
        i++
        continue
      }
      j = next[j - 1]
    }
  }
  return next
}
// getNext()
function kpm (str = 'mississippi', substr = 'issip', next = getNext()) {
  let i = 0
  let j = 0
  while (i < str.length && j < substr.length) {
    if (str[i] === substr[j]) {
      ++i
      ++j
    } else {
      if (j === 0) {
        i++
        continue
      }
      j = next[j - 1]
    }
  }
  if (j >= substr.length) {
    return i - substr.length
  } {
    return 0
  }
}

console.log(kpm())